package protocol

import (
	"context"
	"fmt"
	"time"

	"gb28181/internal/manager"
)

// MessageHandler 消息处理器
type MessageHandler struct {
	clientMgr *manager.ClientManager
}

// NewMessageHandler 创建消息处理器
func NewMessageHandler(clientMgr *manager.ClientManager) *MessageHandler {
	return &MessageHandler{
		clientMgr: clientMgr,
	}
}

// HandleMessage 处理GB28181消息
func (h *MessageHandler) HandleMessage(msg *GB28181Message) (*GB28181Response, error) {
	if !IsValidMessageType(msg.CmdType) {
		return nil, fmt.Errorf("无效的消息类型: %s", msg.CmdType)
	}

	switch msg.CmdType {
	case MessageTypeRegister:
		return h.handleRegister(msg)
	case MessageTypeKeepalive:
		return h.handleKeepalive(msg)
	case MessageTypeCatalog:
		return h.handleCatalog(msg)
	case MessageTypeDeviceInfo:
		return h.handleDeviceInfo(msg)
	case MessageTypeDeviceStatus:
		return h.handleDeviceStatus(msg)
	case MessageTypeDeviceControl:
		return h.handleDeviceControl(msg)
	default:
		return &GB28181Response{
			CmdType: msg.CmdType,
			SN:      msg.SN,
			DeviceID: msg.DeviceID,
			Result:  "ERROR",
			Info:    "暂不支持的消息类型",
		}, nil
	}
}

// handleRegister 处理设备注册消息
func (h *MessageHandler) handleRegister(msg *GB28181Message) (*GB28181Response, error) {
	if msg.DeviceID == "" {
		return &GB28181Response{
			CmdType: MessageTypeRegister,
			SN:      msg.SN,
			DeviceID: msg.DeviceID,
			Result:  "ERROR",
			Info:    "设备ID不能为空",
		}, nil
	}

	ctx := context.Background()
	
	// 这里简化处理，实际应该从消息中获取SIP服务器信息
	sipServerID := "34020000002000000001"
	sipServerHost := "192.168.1.100"
	sipUri := fmt.Sprintf("sip:%s@%s", msg.DeviceID, sipServerHost)
	
	_, err := h.clientMgr.Register(ctx, msg.DeviceID, sipServerID, sipUri)
	if err != nil {
		return &GB28181Response{
			CmdType: MessageTypeRegister,
			SN:      msg.SN,
			DeviceID: msg.DeviceID,
			Result:  "ERROR",
			Info:    fmt.Sprintf("注册失败: %v", err),
		}, nil
	}

	return &GB28181Response{
		CmdType: MessageTypeRegister,
		SN:      msg.SN,
		DeviceID: msg.DeviceID,
		Result:  "OK",
		Info:    "设备注册成功",
	}, nil
}

// handleKeepalive 处理心跳消息
func (h *MessageHandler) handleKeepalive(msg *GB28181Message) (*GB28181Response, error) {
	if msg.DeviceID == "" {
		return &GB28181Response{
			CmdType: MessageTypeKeepalive,
			SN:      msg.SN,
			DeviceID: msg.DeviceID,
			Result:  "ERROR",
			Info:    "设备ID不能为空",
		}, nil
	}

	ctx := context.Background()
	h.clientMgr.UpdateHeartbeat(ctx, msg.DeviceID)

	return &GB28181Response{
		CmdType: MessageTypeKeepalive,
		SN:      msg.SN,
		DeviceID: msg.DeviceID,
		Result:  "OK",
		Info:    "心跳更新成功",
	}, nil
}

// handleCatalog 处理设备目录查询
func (h *MessageHandler) handleCatalog(msg *GB28181Message) (*GB28181Response, error) {
	devices := h.clientMgr.ListDevices()
	
	deviceInfos := make([]DeviceInfo, 0, len(devices))
	for _, device := range devices {
		status := "OFF"
		if device.IsOnline() {
			status = "ON"
		}
		
		deviceInfos = append(deviceInfos, DeviceInfo{
			DeviceID:     device.DeviceId,
			Name:         device.DeviceId,
			Manufacturer: "Unknown",
			Model:        "Unknown",
			Status:       status,
			IPAddress:    "0.0.0.0",
			Port:         "5060",
		})
	}

	response := &GB28181Response{
		CmdType:  MessageTypeCatalog,
		SN:       msg.SN,
		DeviceID: msg.DeviceID,
		Result:   "OK",
	}

	if len(deviceInfos) > 0 {
		response.Info = fmt.Sprintf("找到 %d 个设备", len(deviceInfos))
	} else {
		response.Info = "未找到设备"
	}

	return response, nil
}

// handleDeviceInfo 处理设备信息查询
func (h *MessageHandler) handleDeviceInfo(msg *GB28181Message) (*GB28181Response, error) {
	if msg.DeviceID == "" {
		return &GB28181Response{
			CmdType: MessageTypeDeviceInfo,
			SN:      msg.SN,
			DeviceID: msg.DeviceID,
			Result:  "ERROR",
			Info:    "设备ID不能为空",
		}, nil
	}

	device, exists := h.clientMgr.GetDevice(msg.DeviceID)
	if !exists {
		return &GB28181Response{
			CmdType: MessageTypeDeviceInfo,
			SN:      msg.SN,
			DeviceID: msg.DeviceID,
			Result:  "ERROR",
			Info:    "设备不存在",
		}, nil
	}

	status := "OFF"
	if device.IsOnline() {
		status = "ON"
	}

	return &GB28181Response{
		CmdType:  MessageTypeDeviceInfo,
		SN:       msg.SN,
		DeviceID: msg.DeviceID,
		Result:   "OK",
		Status:   status,
		Info:     fmt.Sprintf("设备ID: %s, SIP URI: %s, 最后心跳: %s", 
			device.DeviceId, device.SipUri, device.LastHeartbeat.Format(time.RFC3339)),
	}, nil
}

// handleDeviceStatus 处理设备状态查询
func (h *MessageHandler) handleDeviceStatus(msg *GB28181Message) (*GB28181Response, error) {
	if msg.DeviceID == "" {
		return &GB28181Response{
			CmdType: MessageTypeDeviceStatus,
			SN:      msg.SN,
			DeviceID: msg.DeviceID,
			Result:  "ERROR",
			Info:    "设备ID不能为空",
		}, nil
	}

	device, exists := h.clientMgr.GetDevice(msg.DeviceID)
	if !exists {
		return &GB28181Response{
			CmdType: MessageTypeDeviceStatus,
			SN:      msg.SN,
			DeviceID: msg.DeviceID,
			Result:  "ERROR",
			Info:    "设备不存在",
		}, nil
	}

	status := "OFF"
	if device.IsOnline() {
		status = "ON"
	}

	return &GB28181Response{
		CmdType:  MessageTypeDeviceStatus,
		SN:       msg.SN,
		DeviceID: msg.DeviceID,
		Result:   "OK",
		Status:   status,
		Info:     fmt.Sprintf("设备状态: %s", status),
	}, nil
}

// handleDeviceControl 处理设备控制消息
func (h *MessageHandler) handleDeviceControl(msg *GB28181Message) (*GB28181Response, error) {
	if msg.DeviceID == "" {
		return &GB28181Response{
			CmdType: MessageTypeDeviceControl,
			SN:      msg.SN,
			DeviceID: msg.DeviceID,
			Result:  "ERROR",
			Info:    "设备ID不能为空",
		}, nil
	}

	_, exists := h.clientMgr.GetDevice(msg.DeviceID)
	if !exists {
		return &GB28181Response{
			CmdType: MessageTypeDeviceControl,
			SN:      msg.SN,
			DeviceID: msg.DeviceID,
			Result:  "ERROR",
			Info:    "设备不存在",
		}, nil
	}

	// 这里简化处理，实际应该根据PTZCmd执行具体的控制操作
	if msg.PTZCmd != "" {
		return &GB28181Response{
			CmdType:  MessageTypeDeviceControl,
			SN:       msg.SN,
			DeviceID: msg.DeviceID,
			Result:   "OK",
			Info:     fmt.Sprintf("执行PTZ控制命令: %s", msg.PTZCmd),
		}, nil
	}

	return &GB28181Response{
		CmdType:  MessageTypeDeviceControl,
		SN:       msg.SN,
		DeviceID: msg.DeviceID,
		Result:   "ERROR",
		Info:     "未指定控制命令",
	}, nil
}

// BuildErrorResponse 构建错误响应
func (h *MessageHandler) BuildErrorResponse(msg *GB28181Message, err error) (*GB28181Response, error) {
	return &GB28181Response{
		CmdType:  msg.CmdType,
		SN:       msg.SN,
		DeviceID: msg.DeviceID,
		Result:   "ERROR",
		Info:     err.Error(),
	}, nil
}